window.onload=function(){
    layui.use(['form','jquery','layer'],function(){
        var form = layui.form, $ = layui.jquery;

        var jumpType='';
        form.on('radio(platform)', function(data){
            if(data.value ==1 ){
                $('.hd').hide();
                $('.sj').hide();
                $('.sp').show();
                if(jumpType!=3){
                    jumpType='';
                }
            }else{
                $('.hd').show();
                $('.sj').show();
                $('.sp').hide();
                if(jumpType==3){
                    jumpType='';
                }
            }
        }); 
        form.on('radio(type)', function(data){
            jumpType = $('input[name="type"]:checked ').val();
        }); 

        var uploader = {
            'data':{
                'token':'',
                'uploadDomain':'',
                'domain':''
            },
            // 'complete':function(res){
            //     var url="http://"+uploader.data.domain +"/"+ res.key;
            //     $(".pic-pic").attr("src",url);
            //     $(".hidden-pic").val(res.key);
            // },
            'error':function () {
                console.dir(arguments);
            },
            // 分片上传时的进度展示功能在此书写.
            'next':function (response) {
                // var chunks = response.chunks || [];
            },
            'init':function(){
                $.ajax({
                    'url':'/upload/get-token',
                    'type':'POST',
                    'dataType':'json',
                    'success':function(data){
                        if(data.code != 200)
                        {
                            layer.alert(data.msg);
                            return false;
                        }
                        uploader.data.token = data.data.token;      // token
                        uploader.data.domain = data.data.domain;    // 显示域名
                        // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                    }
                });
            },
            'eventBind':function(){
                this.init();
                $('.bannerpic').on('change',function (e) {
                    var fileList=e.target.files[0];
                    UpladFile(fileList,'.pic-pic','.hidden-pic','.default')
                });
                function UpladFile(ele,showPic,hiddenPic,deFault) {
                    var fileObj = ele; // js 获取文件对象
                    var formData = new FormData(); // FormData 对象
                    if(fileObj.size/1024 > 200) { //大于200k，进行压缩上传
                        photoCompress(fileObj, {quality: 0.9}, function(base64Codes){
                            //console.log("压缩后：" + base.length / 1024 + " " + base);
                            var bl = convertBase64UrlToBlob(base64Codes);
                            formData.append("file", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件对象
                            
                            var token = uploader.data.token;
                            var config = {
                                useCdnDomain: true,
                                disableStatisticsReport: false,
                                region: qiniu.region.z0
                            };
                            var putExtra = {
                                fname: "",
                                params: {},
                                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                            };
                            // var file = this.files[0];
                            bl.name=fileObj.name;
                            var file=bl;
                            if(TestFileSuffix(file.name) < 0){
                                layer.msg('请上传 jpg/png 类型图片');return;
                            }
                            var observable;
                            if (file) {
                                // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                                var files=file;
                                var key1=file.name;
                                var key=key1.split(".")[0]+Date.parse(new Date())+"."+key1.split(".")[1];
                                putExtra.params["x:name"] = key.split(".")[0];
                                // 配置完成的数组.
                                if(showPic=='.pic-pic'){
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res){
                                            var url="http://"+uploader.data.domain +"/"+ res.key;
                                            $(deFault).hide();
                                            $(showPic).show().attr("src",url);
                                            $(hiddenPic).val(res.key);
                                        }
                                    };
                                }
                                
                                var subscription;
                                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                                observable = qiniu.upload(files, key, token, putExtra, config);
                                subscription = observable.subscribe(subObject);
                                // subscription.unsubscribe();  // 取消上传.
                            }
                            
                        });
                    }else{
                        var token = uploader.data.token;
                        var config = {
                            useCdnDomain: true,
                            disableStatisticsReport: false,
                            region: qiniu.region.z0
                        };
                        var putExtra = {
                            fname: "",
                            params: {},
                            mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                        };
                        var file = fileObj;
                        // bl.name=fileObj.name;
                        // var file=bl;
                        if(TestFileSuffix(file.name) < 0){
                            layer.msg('请上传 jpg/png 类型图片');return;
                        }
                        var observable;
                        if (file) {
                            // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                            var files=file;
                            var key1=file.name;
                            var key=key1.split(".")[0]+Date.parse(new Date())+"."+key1.split(".")[1];
                            putExtra.params["x:name"] = key.split(".")[0];
                            // 配置完成的数组.
                            if(showPic=='.pic-pic'){
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res){
                                        var url="http://"+uploader.data.domain +"/"+ res.key;
                                        $(deFault).hide();
                                        $(showPic).show().attr("src",url);
                                        $(hiddenPic).val(res.key);
                                    }
                                };
                            }
                            
                            var subscription;
                            // 调用sdk上传接口获得相应的observable，控制上传和暂停
                            observable = qiniu.upload(files, key, token, putExtra, config);
                            subscription = observable.subscribe(subObject);
                            // subscription.unsubscribe();  // 取消上传.
                        }
                    }
                }
        
                function photoCompress(file,w,objDiv){
                    var ready=new FileReader();
                        /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
                        ready.readAsDataURL(file);
                        ready.onload=function(){
                            var re=this.result;
                            canvasDataURL(re,w,objDiv)
                        }
                }
                function canvasDataURL(path, obj, callback){
                    var img = new Image();
                    img.src = path;
                    img.onload = function(){
                    var that = this;
                    // 默认按比例压缩
                    var w = that.width,
                    h = that.height,
                    scale = w / h;
                    w = obj.width/1.2 || w/1.2;
                    h = obj.height/1.2 || (w / scale)/1.2;
                    var quality = 0.8;  // 默认图片质量为0.7
                    //生成canvas
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 创建属性节点
                    var anw = document.createAttribute("width");
                    anw.nodeValue = w;
                    var anh = document.createAttribute("height");
                    anh.nodeValue = h;
                    canvas.setAttributeNode(anw);
                    canvas.setAttributeNode(anh); 
                    ctx.drawImage(that, 0, 0, w, h);
                    // 图像质量
                    if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                    quality = obj.quality;
                    }
                    // quality值越小，所绘制出的图像越模糊
                    var base64 = canvas.toDataURL('image/jpeg', quality);
                    // 回调函数返回base64的值
                    callback(base64);
                    }
                }
                /**  
                 * 将以base64的图片url数据转换为Blob  
                 * @param urlData  
                 *            用url方式表示的base64图片数据  
                 */  
                function convertBase64UrlToBlob(urlData){  
                    var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while(n--){
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new Blob([u8arr], {type:mime});
                }
            }
        };

        uploader.eventBind();

        $('#qued').click(function () {
            //表单序列化
            // jumpType = $('input[name="type"]:checked ').val();
            var platform = $('input[name="platform"]:checked ').val();
            var img_url = $('.hidden-pic').val();
            var oid = $('.oid').val();
            flag = true;
            if(jumpType == ""){
                layer.msg("请选择类型");
                flag=false;
            }else if(platform == ""){
                layer.msg("请选择显示平台");
                flag=false;
            }else if(oid==""){
                layer.msg("请输入对象ID");
                flag=false;
            }else if(img_url==""){
                layer.msg("请上传图片");
                flag=false;
            }
            if(flag) {
                $.ajax({
                    'type': 'POST',
                    'url': '/banner/banner-add',
                    'dataType': 'json',
                    'async': false,
                    'data': {'img_url': img_url, 'type': jumpType, 'oid': oid, 'show_platform':platform},
                    success: function (data) {
                        if (data.code == '-1') {
                            Utils.layer.msg("未添加成功，请重试")
                        } else if (data.code == '200') {
                            Utils.layer.msg(data.msg)
                            setTimeout(function(){
                                location.href = "/banner/banner-index"
                            },1200)
                        }
                    },
                    error: function () {
                        Utils.layer.alert("添加失败，请重新添加 ");
                    },
                });
            }
        })
    })
}

